package com.king.security.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.king.security.base.Result;
import com.king.security.enums.RedisKeyEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * APP环境下认证成功处理器
 *
 * @author TiHom
 */
@Component("tiHomAuthenticationSuccessHandler")
public class TiHomAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ObjectMapper objectMapper;


    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                        Authentication authentication) throws IOException, ServletException {
        logger.info("登录成功");
        if (false) {
            String header = httpServletRequest.getHeader("Authorization");
            if (header == null || !header.startsWith("Basic ")) {
                httpServletResponse.getWriter().write(objectMapper.writeValueAsString(Result.buildError("请求头中无client信息")));
                return;
            }
            //抽取并且解码请求头里的字符串
            String[] tokens = this.extractAndDecodeHeader(header, httpServletRequest);

            assert tokens.length == 2;

            String clientId = tokens[0];
            String clientSecret = tokens[1];
        }
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        Object credentials = authentication.getCredentials();
        if (credentials == null) {
            httpServletResponse.getWriter().write(objectMapper.writeValueAsString(Result.buildError("请求头中无client信息")));
            return;
        }
        User u = (User) credentials;
        String token = UUID.randomUUID().toString();
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        //将authentication这个对象转成json格式的字符串
        redisTemplate.opsForValue().set(RedisKeyEnum.LOGIN_USER + token, u.getUsername(), 60 * 60 * 60 * 2L, TimeUnit.SECONDS);
        httpServletResponse.getWriter().write(objectMapper.writeValueAsString(objectMapper.writeValueAsString(Result.buildSuccess(
                new HashMap<String, Object>(1) {{
                    put("token", token);
                }}
        ))));
    }

    private String[] extractAndDecodeHeader(String header, HttpServletRequest request) throws IOException {
        byte[] base64Token = header.substring(6).getBytes("UTF-8");

        byte[] decoded;
        try {
            decoded = Base64.decode(base64Token);
        } catch (IllegalArgumentException var7) {
            throw new BadCredentialsException("Failed to decode basic authentication token");
        }

        String token = new String(decoded, "UTF-8");
        int delim = token.indexOf(":");
        if (delim == -1) {
            throw new BadCredentialsException("Invalid basic authentication token");
        } else {
            return new String[]{token.substring(0, delim), token.substring(delim + 1)};
        }
    }
}
